#include "MainWindow.h"
#include <Ogre.h>

MainWindow::MainWindow(QWidget *parent, Qt::WFlags flags)
    : QMainWindow(parent, flags), root(0)
{
    setupUi(this);

    if(!SetupOgre()) return;

    ogreWidget = new OgreWidget(renderWidget);

    LoadResources();

    scriptPlugin = ScriptManager::getSingleton().GetScriptPlugin("V8");
    if(scriptPlugin) {
        scriptPlugin->Setup(ogreWidget->sceneManager, ogreWidget->camera, ogreWidget->viewport);
    }
}

MainWindow::~MainWindow()
{
    if(scriptManager) OGRE_DELETE scriptManager;
    if(root) OGRE_DELETE root;
}

bool MainWindow::SetupOgre()
{
    try {
        scriptManager = OGRE_NEW ScriptManager();
        root = OGRE_NEW Root("plugins.cfg", "", "ScriptingApp.log");

        RenderSystem* renderSystem = 0;

        foreach(RenderSystem* rsys, root->getAvailableRenderers()) {
            if(rsys->getName() == rsysName) {
                renderSystem = rsys;
                break;
            }
        }

        if(!renderSystem) {
            Ogre::String message;
            message.append("Error: Render system ").append(rsysName).append(" cannot be found.");
            LogManager::getSingleton().logMessage(message);
            throw (message);
        }
            
        renderSystem->setConfigOption("VSync", "Yes");
        renderSystem->setConfigOption("FSAA", "0");
        renderSystem->setConfigOption( "Full Screen", "No" );

        root->setRenderSystem(renderSystem);
        root->initialise(false);

        return true;
    }
    catch (...) {
        if (root) {
            LogManager* logManager = LogManager::getSingletonPtr();
            if (logManager) {
                logManager->logMessage("OGRE INITIALIZATION FAILED: Shutting down Ogre.");
            }
            OGRE_DELETE root;
            root = 0;
        }
        return false;
    }
}

void MainWindow::on_runScript_clicked()
{
    if(scriptPlugin) {
        Ogre::String code(scriptEdit->toPlainText().toUtf8());
        if(!scriptPlugin->Execute(code)) {
            std::cerr << scriptPlugin->Error();
        } else {
            std::cout << scriptPlugin->Result();
        }
    }

    ogreWidget->UpdateOgre();
}

void MainWindow::LoadResources()
{
    LocateResources();
    Ogre::ResourceGroupManager& rgm = Ogre::ResourceGroupManager::getSingleton();
	rgm.initialiseAllResourceGroups();
}

void MainWindow::LocateResources()
{
    // load resource paths from config file
    Ogre::ConfigFile cf;
    cf.load("resources.cfg");

    Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
    Ogre::String sec, type, arch;
    Ogre::ResourceGroupManager& resourceGroupManager = Ogre::ResourceGroupManager::getSingleton();

    // go through all specified resource groups
    while (seci.hasMoreElements())
    {
        sec = seci.peekNextKey();
        Ogre::ConfigFile::SettingsMultiMap* settings = seci.getNext();
        Ogre::ConfigFile::SettingsMultiMap::iterator i;

        // go through all resource paths
        for (i = settings->begin(); i != settings->end(); i++)
        {
            type = i->first;
            arch = i->second;

            #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE || OGRE_PLATFORM == OGRE_PLATFORM_IPHONE
            // OS X does not set the working directory relative to the app,
            // In order to make things portable on OS X we need to provide
            // the loading with it's own bundle path location
            if (!Ogre::StringUtil::startsWith(arch, "/", false)) // only adjust relative dirs
            arch = Ogre::String(Ogre::macBundlePath() + "/" + arch);
            #endif
            resourceGroupManager.addResourceLocation(arch, type, sec);
        }
    }
}